package com.yuanlrc.base.controller.admin;

import com.yuanlrc.base.bean.CodeMsg;
import com.yuanlrc.base.bean.PageBean;
import com.yuanlrc.base.bean.Result;
import com.yuanlrc.base.constant.SessionConstant;
import com.yuanlrc.base.entity.admin.*;
import com.yuanlrc.base.service.admin.*;
import com.yuanlrc.base.util.SessionUtil;
import com.yuanlrc.base.util.ValidateEntityUtil;
import org.apache.catalina.manager.util.SessionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 图书的控制层
 */
@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;

    @Autowired
    private BookCategoryService categoryService;

    @Autowired
    private OperaterLogService operaterLogService;

    @Resource
    private BorrowService borrowService;

    @Autowired
    private StudentService studentService;

    /**
     * 图书列表页面
     * @param model
     * @param book
     * @param pageBean
     * @return
     */

//    @RequestMapping(value = "/list")
//    public String list(Model model, Book book, PageBean<Book> pageBean) {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        model.addAttribute("title", "图书列表");
//        model.addAttribute("bookName", book.getBookName());
//        model.addAttribute("pageBean", bookService.findList(book, pageBean));
//        model.addAttribute("books", bookService.findAll());
//        model.addAttribute("datetime",sdf.format(new Date()));
//        return "admin/book/list";
//    }
    @RequestMapping(value = "/list")
    public String list(Model model, Book book, PageBean<Book> pageBean) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        model.addAttribute("title", "图书列表");
        model.addAttribute("pageBean", bookService.findList(book, pageBean));
        model.addAttribute("books", bookService.findAll());
        model.addAttribute("datetime",sdf.format(new Date()));
        return "admin/book/list";
    }

    /**
     * 根据一级分类id 查询二级分类
     * @param id
     * @return
     */
    @RequestMapping(value = "/category")
    @ResponseBody
    public List<BookCategory> category(Long id) {
        List<BookCategory> categoryByParentId = bookService.findCategoryByParentId(id);
        System.out.println("categoryByParentId = " + categoryByParentId);
        return categoryByParentId;
    }


    /**
     * 新增图书页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model) {
        model.addAttribute("categories", bookService.findparent());
        return "admin/book/add";
    }


    /**
     * 图书添加表单提交处理
     *
     * @param book
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> add(Book book) {
        //用统一验证实体方法验证是否合法
        CodeMsg validate = ValidateEntityUtil.validate(book);
        if (validate.getCode() != CodeMsg.SUCCESS.getCode()) {
            return Result.error(validate);
        }
        //图书一级分类要选择
        if(book.getCategory() == null || book.getCategory().getId() == null){
            return Result.error(CodeMsg.ADMIN_BOOK_CATEGORY_ERROR);
        }
        //图书二级分类需要选择
        if(book.getParent() == null || book.getParent().getId() == null )
        {
            return Result.error(CodeMsg.ADMIN_BOOK_CATEGORY_ERROR);
        }
        if(book.getCannum() < -1)
        {
            return Result.error(CodeMsg.ADMIN_BORROW_ADD_NUM_ERROR);
        }
        //判断图书名是否存在
        if (bookService.isExistbookName(book.getBookName(), 0L)) {
            return Result.error(CodeMsg.ADMIN_BOOK_NAME_EXIST_ERROR);
        }
        //到这说明一切符合条件，进行数据库新增
        if (bookService.save(book) == null) {
            return Result.error(CodeMsg.ADMIN_BOOK_ADD_ERROR);
        }
        operaterLogService.add("添加图书，图书名称：" + book.getBookName());
        return Result.success(true);
    }


    /**
     * 图书编辑页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, @RequestParam(name = "id", required = true) Long id) {
        Book book = bookService.find(id);
        BookCategory category = book.getCategory();
        BookCategory parent = book.getParent();
        Long categoryId = 0L;
        Long parentId = 0L;
        Long parentId2 = 0L;
        if(category != null && category.getId() != null)
            categoryId = category.getId();

        if(parent != null && parent.getId() != null)
            parentId = parent.getId();

        if(book.getCategory() != null && book.getCategory().getParent() != null)
            parentId2 = book.getCategory().getParent().getId();

        model.addAttribute("categories", categoryService.findAll());
        model.addAttribute("categories2", bookService.findparent());
        model.addAttribute("book", book);
        model.addAttribute("categoryId", categoryId);
        model.addAttribute("parentId",parentId);
        model.addAttribute("parentId2",parentId2);
        return "admin/book/edit";
    }
    /**
     * 编辑图书信息表单提交处理
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> edit(Book book) {
        //用统一验证实体方法验证是否合法
        CodeMsg validate = ValidateEntityUtil.validate(book);
        if (validate.getCode() != CodeMsg.SUCCESS.getCode()) {
            return Result.error(validate);
        }
        //图书一级分类要选择
        if(book.getCategory() == null || book.getCategory().getId() == null){
            return Result.error(CodeMsg.ADMIN_BOOK_CATEGORY_ERROR);
        }

        //图书二级分类需要选择
        if(book.getParent() == null || book.getParent().getId() == null )
        {
            return Result.error(CodeMsg.ADMIN_BOOK_CATEGORY_ERROR);
        }

        if(book.getCannum() < -1)
        {
            return Result.error(CodeMsg.ADMIN_BORROW_ADD_NUM_ERROR);
        }

        if (bookService.isExistbookName(book.getBookName(), book.getId())) {
            return Result.error(CodeMsg.ADMIN_BOOK_NAME_EXIST_ERROR);
        }
        //到这说明一切符合条件，进行数据库保存
        Book findById = bookService.find(book.getId());
        //讲提交的图书信息指定字段复制到已存在的user对象中,该方法会覆盖新字段内容
        BeanUtils.copyProperties(book, findById, "id", "createTime", "updateTime");
        if (bookService.save(findById) == null) {
            return Result.error(CodeMsg.ADMIN_BOOK_EDIT_ERROR);
        }
        operaterLogService.add("编辑图书，图书名称：" + book.getBookName());
        return Result.success(true);
    }

    /**
     * 删除图书
     * @param id
     * @return
     */

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> delete(@RequestParam(name = "id", required = true) Long id) {
        try {
            bookService.delete(id);
        } catch (Exception e) {
            return Result.error(CodeMsg.ADMIN_BOOK_DELETE_ERROR);
        }
        operaterLogService.add("添加图书，图书ID：" + id);
        return Result.success(true);
    }

    @RequestMapping(value = "/sss")
    @ResponseBody
    public List<BookCategory> findparent() {
        return bookService.findparent();
    }


    /**
     * 图书的借阅
     * @param borrow
     * @param datetime
     * @return
     */
    @RequestMapping(value ="/addBorrow", method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> borrow(Borrow borrow, String datetime) {
        if(datetime == null)
            return Result.error(CodeMsg.ADMIN_BOOK_BORROW_DATETIME_ERROR);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try
        {
            date = sdf.parse(datetime);
        }catch (Exception e)
        {
            return Result.error(CodeMsg.ADMIN_BOOK_BORROW_DATETIME_ERROR);
        }
        if(date != null)
        {
            Date now = new Date();
            if(now.compareTo(date) > 0)
            {
                return  Result.error(CodeMsg.ADMIN_BOOK_BORROW_DATETIME_ERROR);
            }
        }
        if(borrow == null)
        {
            return Result.error(CodeMsg.ADMIN_BOOK_BORROW_ERROR);
        }

        if(borrow.getBook() == null)
        {
            return Result.error(CodeMsg.ADMIN_BOOK_EXIST_ERROR);
        }
        else
        {
            if(borrow.getBook().getId() == null)
                return Result.error(CodeMsg.ADMIN_BOOK_EXIST_ERROR);
        }
        CodeMsg codeMsg = ValidateEntityUtil.validate(borrow);
        if(codeMsg.getCode() != CodeMsg.SUCCESS.getCode())
        {
            return Result.error(CodeMsg.ADMIN_BORROW_ADD_ERROR);
        }
        Book book = bookService.find(borrow.getBook().getId());
        if(book.getState() == Book.BOOK_NORMAL)
            return Result.error(CodeMsg.ADMIN_BOOK_STATUS_ERROR);
        //获取到库存数量
        Integer count = book.getCannum();
        borrow.setBook(book);
        borrow.setBorrowState(0);
        borrow.setExpectedReturnTime(date);
        borrow.setBookName(book.getBookName());
        borrow.setOverTime(0);
        borrow.setReturnTime(null);
        Student stu = null;
        try
        {
            stu = studentService.find(SessionUtil.getLoginedStudent().getId());
        }catch (Exception e)
        {
            return Result.error(CodeMsg.ADMIN_USE_NO_EXIST);
        }
        if(stu == null)
            return Result.error(CodeMsg.ADMIN_USE_NO_EXIST);
        borrow.setStudent(stu);

        if (borrow.getBorrowNum() > count)
        {
            return Result.error(CodeMsg.ADMIN_BOOK_BORROW_NUMBER_ERROR);
        }
        book.setCannum(book.getCannum() - borrow.getBorrowNum());
        if(book.getCannum() == 0)
        {
            book.setState(Book.BOOK_NORMAL);
        }
        if(borrowService.save(borrow) == null)
        {
            return Result.error(CodeMsg.ADMIN_BORROW_ADD_ERROR);
        }
        Long id = book.getId();
        Book findId = bookService.find(id);
        findId.setState(book.getState());
        findId.setCannum(book.getCannum());
        findId.setNum(findId.getNum() + borrow.getBorrowNum());
        if(bookService.save(findId) == null)
        {
            return Result.error(CodeMsg.ADMIN_BOOK_EDIT_ERROR);
        }
        return Result.success(true);
    }
}
